package com.itheima.reggie.contronller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.MyContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/addressBook")
public class AddressBookContronller {

    @Autowired
    private AddressBookService addressBookService;

    @PostMapping
    public R<String> addAddressBook(@RequestBody AddressBook addressBook) {

        Long id = MyContext.getLoginId();
        addressBook.setUserId(id);
        addressBookService.save(addressBook);


        return R.success("地址添加成功");
    }

    @GetMapping("/list")
    public R<List<AddressBook>> list() {


        Long id = MyContext.getLoginId();
        LambdaQueryWrapper<AddressBook> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(AddressBook::getUserId, id)
                .orderByDesc(AddressBook::getUpdateTime);

        List<AddressBook> list = addressBookService.list(lambdaQueryWrapper);
        //查询当前所有地址是否有默认地址没有的话就将第一个地址自动设置成默认
        for (AddressBook addressBook : list) {
            if (addressBook.getIsDefault() == 1) {
                return R.success(list);
            }
        }
        //说明没有默认值
        //第一个地址自动设置成默认,并同步数据库

        AddressBook addressBook = list.get(0);
        addressBook.setIsDefault(1);
        addressBookService.updateById(addressBook);
        return R.success(list);
    }

    @PutMapping("/default")
    public R<String> setDefault(@RequestBody AddressBook addressBook) {

        addressBookService.setDefault(addressBook);
        return R.success("设置默认地址成功");
    }

    @GetMapping("/{id}")
    public R<AddressBook> getOne(@PathVariable Long id) {

        return R.success(addressBookService.getById(id));
    }

    @PutMapping
    public R<String> update(@RequestBody AddressBook addressBook) {
        addressBook.setUpdateTime(null);
        addressBook.setUpdateUser(null);
        addressBookService.updateById(addressBook);

        return R.success("修改成功");
    }

    @DeleteMapping
    public R<String> deleteByIds(@RequestParam List<Long> ids) {

        addressBookService.removeByIds(ids);

        return R.success("删除成功");
    }

    @GetMapping("/default")
    public R<AddressBook> defaultAddress() {

        //查询该地址表里对应userID的默认值为1的数据
        Long userId = MyContext.getLoginId();
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getUserId, userId).eq(AddressBook::getIsDefault, 1);
        AddressBook one = addressBookService.getOne(lqw, false);
        if (one == null){
            return R.error("您还未添加地址");
        }
        return R.success(one);
    }
}
